package edu.ynu.hhy.architectureclass.service;

import edu.ynu.hhy.architectureclass.common.service.LogicService;
import edu.ynu.hhy.architectureclass.dao.DeviceDao;
import edu.ynu.hhy.architectureclass.entity.Device;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DeviceService extends LogicService<DeviceDao, Device, Long> {
    @Autowired
    public DeviceService(DeviceDao deviceDao) {
        super(deviceDao);
    }

    @Autowired
    private DeviceDao deviceDao;

    /**
     * 根据设备序列号查找设备
     */
    public Device findBySerialNumber(String serialNumber) {
        return deviceDao.findBySerialNumber(serialNumber);
    }

    /**
     * 绑定设备到大棚
     *
     * @param deviceId     设备ID
     * @param greenhouseId 大棚ID
     * @return 绑定后的设备
     */
    public Device bindDeviceToGreenhouse(Long deviceId, Long greenhouseId) {
        Device device = GET(deviceId);
        if (device != null) {
            // 绑定逻辑
            device.setId(greenhouseId);
            return PUT(device);
        }
        return null;
    }
    /**
     * 获取设备表中的前五个 serialNumber
     */
    public List<String> getFirstFiveDeviceSerials() {
        List<Device> devices = deviceDao.findFirst5ByOrderByIdAsc();
        return devices.stream()
                .map(Device::getSerialNumber)
                .collect(Collectors.toList());
    }

    /**
     * 获取所有 category 为 "sensor" 的设备的 serialNumber
     */
    public List<String> getAllSensorDeviceSerials(){
        // 查询所有 category 为 "sensor" 的设备
        List<Device> sensorDevices = deviceDao.findByCategory("sensor");

        // 提取 serialNumber
        return sensorDevices.stream()
                .map(Device::getSerialNumber)
                .collect(Collectors.toList());
    }
}